#include "server.h"
#include <QtGui>
#include <QtNetwork>
#include <QDateTime>
#include <QtXml>
#include "client.h"

server::server(QObject * parent) : QThread(parent)
{
    ServerName = "";
    ServerPort = 2600;
    ServerInfoPort = 8080;
    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);
}

void server::run()
{
    while(true)
    {
        ReadClients();

        msleep(10);
    }
}

void server::ReadClients()
{
    //if(client.count()<1) return;

    for( int i = 0; i < client.size(); ++i)
    {
        QString element;
        QString xmlstring = client[i]->Read();
        if(Get(element, xmlstring, QString("NickName")) )
        {
            client[i]->NickName = element;
            emit clientsUpdated();
        }

    }
}

bool server::Get(QString &string, QString &source, QString NodeName)
{
    QDomDocument domDocument;
    domDocument.setContent(source);
    //QDomElement root;
    //root = domDocument.documentElement();
    //if ( root.tagName() != "ServerInfo" )
    //    return false;
    //QDomElement domElement;
    //domElement = domDocument.firstChildElement(NodeName);
    QDomNodeList domNode;
    domNode = domDocument.elementsByTagName(NodeName);
    //QDomElement domElement = domDocument.elementsByTagName(NodeName).item(1).toElement();
    QDomElement domElement;
    for( int i=0; i< domNode.length(); i++)
    {
        domElement = domNode.at(i).toElement();
    }
    if(domElement.isNull())
        return false;
    string = domElement.text();
    return true;
}

bool server::startServer()
{

    if (!tcpServer->listen(QHostAddress::Any, ServerPort))
    {
        QMessageBox::critical(0,"Server",
            QString("Failure with Server: ").append(tcpServer->errorString())
            );
        return false;
    }
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(Connect()));
    return true;
}

bool server::Connect()
{
    QTcpSocket * tempSocket = tcpServer->nextPendingConnection();
    for( int i = 0; i < client.size(); ++i)
    {
        if(tempSocket->peerAddress() == client[i]->getPeerAddress() )
            return false;
    }

    Client * c = new Client(tempSocket, this);

    client << c;
    connect( client.last(), SIGNAL(finished()), this, SLOT(DeleteClient()) );
    client.last()->start();

    QByteArray block;
    QString string;
    string.append("<ServerInfo>");
    string.append("<ServerName>").append(ServerName).append("</ServerName>");
    string.append("<ServerInfoPort>").append(QString::number(ServerInfoPort)).append("</ServerInfoPort>");
    string.append("<ServerLevel>").append(ServerLevelName).append("</ServerLevel>");
    string.append("</ServerInfo>");
    client.last()->Write(string);
    QMessageBox::about(0, "info",string);
    emit newConnection();
    return true;
}

bool server::Disconnect(int ListItem)
{

    client[ListItem]->End();
    while(client[ListItem]->isRunning())
        msleep(10);
    client.removeAt(ListItem);
    emit clientsUpdated();
    return true;
}

void server::DeleteClient()
{
    for(int i=0; i<client.size(); ++i)
    {
        if(client[i]->isFinished())
        {
            client.removeAt(i);
            emit clientsUpdated();
            return;
        }
    }

}
